#!/usr/bin/env perl

# top -bc -n 1, and then sort by res
# by sykp241095@gmail.com

use strict;
use warnings;

sub sort_by_res {
    my @two = @_;
    s/^ +(.*)$/$1/ foreach @two;
    my ( $a_res, $b_res ) = map { ( split / +/ )[5] } @two;
    &human( $a_res ) <=> &human( $b_res );
}

# transfer 1m to 1 * 1024, 1g to 1 * 1024 * 1024
sub human {
    $_ = shift;
    return $1 * 1024 if m/(\d+(\.\d+)?)m/;
    return $1 * 1024 * 1024 if m/(\d+(\.\d+)?)g/;
    $_;
}

my @lines= `top -bc -n 1`;
my @titles = @lines[0 .. 6];
my @records = reverse sort { &sort_by_res($a, $b) }  @lines[7 .. $#lines-1];

print foreach @titles, @records, "\n";

